﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using Common.Library;
using Microsoft.Phone.BackgroundTransfer;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Tasks;
using MarkHeath.StarRating;
using System.Threading;
using System.Globalization;
using OnlineVideos.Views;
using OnlineVideos.Library;
using OnlineVideos.Common;
using OnlineVideos.UI;
using OnlineVideos.Data;
using OnlineVideos.Entities;
using System.ComponentModel;
using Common.Utilities;
using Microsoft.Phone.BackgroundAudio;
using System.Windows.Resources;
using System.IO;
using OnlineVideos.View_Models;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Phone.Shell;
using FlurryWP8SDK.Models;


namespace OnlineVideos
{
    public partial class Shows : PhoneApplicationPage
    {
        #region Global
        bool IsDataLoaded;
        List<ShowList> objtoprated = null;
        List<ShowList> objrecent = null;
        List<ShowList> objtamil = null;
        List<ShowList> objupcoming = null;
        List<DownloadStatus> download = new List<DownloadStatus>();
        int topratedCount;
        int recentCount;
        int tamilCount;
        int upcomingCount;
        int rateindex;
        string index = string.Empty;
        string youtubeurl;
        private WebClient webClient1 = new WebClient();
        #endregion

        #region Constructor

        public Shows()
        {
            try
            {
            InitializeComponent();

            topratedCount = Constants.PageSize;
            recentCount = Constants.PageSize;
            tamilCount = Constants.PageSize;
            upcomingCount = Constants.PageSize;
            rateindex = 0;

            LoadPivotThemes();
            LoadDownLoadTheme();
            IsDataLoaded = false;
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in Shows Method In Shows file.", ex);
            }
          
        }

        #endregion

        #region PageLoad
       
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
            LoadAds();
            try
            {
                FlurryWP8SDK.Api.LogEvent("Shows Page", true);
                if (ResourceHelper.ProjectName != "Web Tile" && ResourceHelper.ProjectName != "Video Mix")
            {
                ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                b.Text = "Add" + " " + AppResources.Type;
            }
            else
            {
                ApplicationBar.IsVisible = false;
            }
            if (IsDataLoaded == false)
            {
                if (rateindex != 0)
                {
                    pvtVideos.SelectedIndex = rateindex;
                    rateindex = 0;
                }

                PageHelper.RemoveEntryFromBackStack("Videos");

                string name = string.Empty;
                if (NavigationContext.QueryString.TryGetValue("name", out name))
                {
                    tblkVideosTitle.Text = name.ToUpper();
                }
              
                if (NavigationContext.QueryString.TryGetValue("index", out index))
                {
                    if (index != "" && index != null)
                    {
                        pvtVideos.SelectedIndex = int.Parse(index);
                       
                    }
                   
                }

                try
                {
                    GetPageDataInBackground();
                }
                catch (Exception ex)
                {
                        Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Shows file.", ex);
                }
            }
            performanceProgressBar.IsIndeterminate = false;
           
        }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Shows file.", ex);
            }
        }

        #endregion
  
        #region "Common Methods"
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstackpl, 2);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        private void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();
            performanceProgressBar.IsIndeterminate = true;
            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineShow.GetTopRatedShows(topratedCount);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            objtoprated = (List<ShowList>)a.Result;
                                            if(objtoprated.Count!=0)
                                            {
                                            lbxTopRated.ItemsSource = (List<ShowList>)a.Result;
                                            tblkToprated.Visibility = Visibility.Collapsed;
                                          
                                            }
                                            else
                                            {
                                                lbxTopRated.ItemsSource = null;
                                                tblkToprated.Visibility = Visibility.Visible;
                                            }
                                            if (ResourceHelper.ProjectName == AppResources.VideoMix)
                                            {
                                                tblkToprated.Text = "No Video mixes Available";
                                            }
                                            performanceProgressBar.IsIndeterminate = false;
                                        }
                                      );

            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineShow.GetRecentlyAddedShows(recentCount);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                             objrecent = (List<ShowList>)a.Result;
                                            if(objrecent.Count!=0)
                                            {
                                            lbxRecentlyAdded.ItemsSource = (List<ShowList>)a.Result;
                                            tblkrecent.Visibility = Visibility.Collapsed;
                                            }
                                            else
                                            {
                                                lbxRecentlyAdded.ItemsSource = null;
                                                tblkrecent.Visibility = Visibility.Visible;
                                            }
                                            if (ResourceHelper.ProjectName == AppResources.VideoMix)
                                            {
                                                tblkrecent.Text = "No Video mixes Available";
                                            }
                                            performanceProgressBar.IsIndeterminate = false;
                                        }
                                      );
            if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
            {
            bwHelper.AddBackgroundTask(
                                      (object s, DoWorkEventArgs a) =>
                                      {
                                          a.Result = OnlineShow.GetTamilAddedShows(tamilCount);
                                      },
                                      (object s, RunWorkerCompletedEventArgs a) =>
                                      {
                                          objtamil = (List<ShowList>)a.Result;
                                          if (objtamil.Count != 0)
                                          {
                                              lbxTamilAdded.ItemsSource = (List<ShowList>)a.Result;
                                              //tblkrecent.Visibility = Visibility.Collapsed;
                                          }
                                          else
                                          {
                                              lbxTamilAdded.ItemsSource = null;
                                              //tblkrecent.Visibility = Visibility.Visible;
                                          }
                                          //if (ResourceHelper.ProjectName == AppResources.VideoMix)
                                          //{
                                          //    tblkrecent.Text = "No Video mixes Available";
                                          //}
                                          performanceProgressBar.IsIndeterminate = false;
                                      }
                                    );
        }
            //if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
            //{
            //    bwHelper.AddBackgroundTask(
            //                              (object s, DoWorkEventArgs a) =>
            //                              {
            //                                  a.Result = OnlineShow.GetUpComingAddedShows(upcomingCount);
            //                              },
            //                              (object s, RunWorkerCompletedEventArgs a) =>
            //                              {
            //                                  objupcoming = (List<ShowList>)a.Result;
            //                                  if (objupcoming.Count != 0)
            //                                  {
            //                                      lbxUpcomingAdded.ItemsSource = (List<ShowList>)a.Result;
            //                                      //tblkrecent.Visibility = Visibility.Collapsed;
            //                                  }
            //                                  else
            //                                  {
            //                                      lbxUpcomingAdded.ItemsSource = null;
            //                                      //tblkrecent.Visibility = Visibility.Visible;
            //                                  }
            //                                  //if (ResourceHelper.ProjectName == AppResources.VideoMix)
            //                                  //{
            //                                  //    tblkrecent.Text = "No Video mixes Available";
            //                                  //}
            //                                  performanceProgressBar.IsIndeterminate = false;
            //                              }
            //                            );
            //}
            if (AppResources.ShowCategoryPivot)
            {
                bwHelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {
                                                if (ResourceHelper.AppName == Apps.Web_Tile.ToString())
                                                {
                                                    a.Result = OnlineShow.LoadCategoryListForWebTile();
                                                }
                                                else if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
                                                {
                                                    a.Result = OnlineShow.LoadCategoryListForCricketVideos();
                                                }
                                                else
                                                {
                                                    a.Result = OnlineShow.LoadCategoryList();
                                                }
                                            },
                                            (object s, RunWorkerCompletedEventArgs a) =>
                                            {
                                                if (ResourceHelper.AppName == Apps.Web_Tile.ToString())
                                                {
                                                    lbxCategory.ItemsSource = (List<ShowCategories>)a.Result;
                                                    performanceProgressBar.IsIndeterminate = false;
                                                }
                                                else if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
                                                {
                                                    lbxCategory.ItemsSource = (List<ShowCategories>)a.Result;
                                                    performanceProgressBar.IsIndeterminate = false;
                                                }
                                                else
                                                {
                                                    lbxCategory.ItemsSource = (List<CatageoryTable>)a.Result;
                                                    performanceProgressBar.IsIndeterminate = false;
                                                }
                                            }
                                          );
            }
            if (AppSettings.AddNewShowIconVisibility == true)
            {
                List<DownloadInfo> objVideoList = new List<DownloadInfo>();
                performanceProgressBar.IsIndeterminate = true;
                bwHelper.AddBackgroundTask(
                                           (object s, DoWorkEventArgs a) =>
                                           {
                                               objVideoList = DownloadManager.LoadDownloadUrls();
                                           },
                                           (object s, RunWorkerCompletedEventArgs a) =>
                                           {
                                               if (objVideoList.Count != 0)
                                               {
                                                   DownLoadList();
                                               }
                                               else
                                               {
                                                   Constants.SaveDownloadList.Clear();
                                                   tblkNoDownloads.Visibility = Visibility.Visible;
                                                   lbxdownloading.Visibility = Visibility.Collapsed;
                                               }
                                               performanceProgressBar.IsIndeterminate = false;
                                           }
                                         );

            }

            bwHelper.RunBackgroundWorkers();
        }

        private void LoadDownLoadTheme()
        {
            if (AppSettings.AddNewShowIconVisibility == true)
            {
                if (ResourceHelper.ProjectName == "Web Tile")
                {
                    pvtdownload.Visibility = Visibility.Collapsed;
                    pvtVideos.Items.Remove(pvtdownload);
                }
                else
                {
                    pvtdownload.Visibility = Visibility.Visible;
                    pvtdownload.Header = "downloads";
                }
            }
            else
            {
                pvtdownload.Visibility = Visibility.Collapsed;
                pvtVideos.Items.Remove(pvtdownload);
            }
        }

        private void LoadPivotThemes()
        {
            
            if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
            {
                pvttop.Header = "hindi";
                pvtrecent.Header = "telugu";
                pvttamil.Header = "tamil";
                pvttamil.Visibility = Visibility.Visible;
                //pvtupcoming.Header = "upcoming movies";
                //pvtupcoming.Visibility = Visibility.Visible;
            }
            else
            {
                pvttop.Header = "top rated";
                pvtrecent.Header = "recent";
                pvttamil.Visibility = Visibility.Collapsed;
                pvtVideos.Items.Remove(pvttamil);
                //pvtupcoming.Visibility = Visibility.Collapsed;
                //pvtVideos.Items.Remove(pvtupcoming);
            }
            if (AppResources.ShowCategoryPivot != true)
            {
                pvtcat.Visibility = Visibility.Collapsed;
                pvtVideos.Items.Remove(pvtcat);
            }
            else
            {
                pvtcat.Header = AppResources.ShowCategoryPivotTitle.Split(',')[1];
                pvtcat.Visibility = Visibility.Visible;
            }
        }

        public void DownLoadList()
        {
            try
            {
               
                List<DownloadInfo> objVideoList = new List<DownloadInfo>();
                download.Clear();
                download.AddRange(Constants.SaveDownloadList);
                if (Constants.DownloadStatus == false)
                objVideoList = DownloadManager.LoadDownloadUrls();
                int countlist = objVideoList.Count();
                if (countlist > 0)
                {
                    List<DownloadInfo> info = new List<DownloadInfo>();
                    var xquery = (from q in objVideoList select q);

                    foreach (var itm in xquery)
                    {
                        var listitm = Constants.SaveDownloadList.Where(k => k.Id == itm.FolderID).FirstOrDefault();
                        if (listitm == null)
                        {
                            List<DownloadStatus> downloadstatuslist = new List<DownloadStatus>();
                           
                            string link = "";
                            link = itm.LinkUrl;
                            string name = "";
                            name = itm.LinkUrl.ToString().Substring(itm.LinkUrl.ToString().LastIndexOf('/') + 1);
                            if (itm.LinkUrl.StartsWith("http://www.youtube.com/watch?v="))
                            {
                                link = itm.LinkUrl.Replace("http://www.youtube.com/watch?v=", "");
                                name = itm.title;
                                name = name.Replace(":", "").Replace("|", "").Replace(".flv", "").Replace(".", "").Replace("&", "").Replace("#", "").Replace(";", "").Replace("title=", "");
                            }
                            var ln = link;
                            WebClient wb = new WebClient();
                            wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownloadList_DownloadProgressChanged);
                            if (itm.LinkUrl.StartsWith("http://www.youtube.com/watch?v="))
                            {
                                wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wcYoutubeReadCompleted_OpenReadCompleted);
                            }
                            else
                            {
                                wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wcDownloadList_OpenReadCompleted);
                            }

                            wb.OpenReadAsync(new Uri(link.ToString(), UriKind.Absolute), itm.FolderID.ToString());
                            downloadstatuslist = DownloadManagerHelper.LoadList(name, link, int.Parse(itm.FolderID.ToString()),"");
                            download.AddRange(downloadstatuslist);
                            Constants.SaveDownloadList.AddRange(downloadstatuslist);
                            Constants.DownloadStatus = true;
                        }

                    }
                }
                else if (Constants.SaveDownloadList.Count == 0)
                {
                    tblkNoDownloads.Visibility = Visibility.Visible;
                    lbxdownloading.Visibility = Visibility.Collapsed;
                }
                lbxdownloading.ItemsSource = null;
                lbxdownloading.ItemsSource = Constants.SaveDownloadList;
            }


            catch (Exception ex)
            {
                string excepmess = "Exception in AddList Method In showlist file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
                Exceptions.SaveOrSendExceptions("Exception in DownLoadList Method In Shows file.", ex);
            }
        }

        private void LoadAudioSongd(string title)
        {
            try
            {
            int Showid = Convert.ToInt32(AppSettings.ShowID);
            string linktype = LinkType.Audio.ToString();
            var ShowLinksByType = Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == Showid && i.LinkType == linktype).ToListAsync()).Result;
            foreach (var linkinfo in ShowLinksByType)
            {
                    AppSettings.AudioTitle = linkinfo.Title;
                if (linkinfo.Title == title)
                {
                    AudioTrack audioTrack = new AudioTrack();
                    audioTrack.BeginEdit();
                    audioTrack.Source = new Uri(linkinfo.LinkUrl, UriKind.RelativeOrAbsolute);
                    audioTrack.Title = linkinfo.Title;
                    audioTrack.EndEdit();
                    BackgroundAudioPlayer.Instance.Track = audioTrack;
                    BackgroundAudioPlayer.Instance.Play();
                    BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
                    AppSettings.AudioShowID = AppSettings.ShowID;
                }
                else
                {
                    BackgroundAudioPlayer.Instance.Pause();
                    AppSettings.SongPlayImage = string.Empty;
                }
            }
        }
            catch (Exception ex)
            {

               Exceptions.SaveOrSendExceptions("Exception in LoadAudioSongd Method In Shows file.", ex);
            }
        }

        private void GetDownloadExtensions()
        {
            try
            {
                string ext = string.Empty;
                try
                {
                    ext = System.IO.Path.GetExtension((lbxRecentlyAdded.SelectedItem as ShowList).Title);
                }
                catch (Exception ex)
                {
                    ext = System.IO.Path.GetExtension((lbxTopRated.SelectedItem as ShowList).Title);
                }
                if (ext == ".3gp" || ext == ".3g2" || ext == ".mp4" || ext == ".m4v" || ext == ".wmv" || (lbxTopRated.SelectedItem as ShowList).TileImage == "videos.jpg")
                {
                    DownloadManagerHelper.Playvideo(int.Parse(AppSettings.ShowID));
                }
                else if (ext == ".mp3" || ext == "=low" || ext == ".wav" || ext == ".aac" || ext == ".amr" || ext == ".wma")
                {
                    try
                    {
                        LoadAudioSongd((lbxRecentlyAdded.SelectedItem as ShowList).Title);
                    }
                    catch (Exception ex)
                    {
                        LoadAudioSongd((lbxTopRated.SelectedItem as ShowList).Title);
                    }
                }
                else if (ext == ".jpg" || ext == ".png")
                {

                    PageHelper.NavigateToDownloadedImagePage(AppResources.DownloadImagePageName);
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in GetDownloadExtensions Method In Shows.cs file.", ex);
            }
        }

        #endregion

        #region Events

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            try
            {
              
                FlurryWP8SDK.Api.EndTimedEvent("Shows Page");
            }
            catch (Exception ex)
            {
                
             Exceptions.SaveOrSendExceptions("Exception in OnNavigatingFrom Method In Shows.cs file.", ex);
            }
            //if (adstackpl.Children.Count > 0)
            //((AdRotator.AdRotatorControl)adstackpl.Children[0]).Dispose();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (AppSettings.AddNewShowIconVisibility)
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml?backentryid=1", UriKind.Relative));
            }
            else
            {
                if (AppSettings.bcount)
                {
                    if (NavigationService.CanGoBack)
                        NavigationService.GoBack();
                }
                else
                {
                    rateindex = 0;
                }
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
            performanceProgressBar.IsIndeterminate = true;
        }
            catch (Exception ex)
            {

                     Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In Shows.cs file.", ex);
            }
        }

        private void lbxTopRated_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {


                if (lbxTopRated.SelectedIndex != -1)
                {

                    AppSettings.ShowID = (lbxTopRated.SelectedItem as ShowList).ShowID.ToString();
                    AppSettings.ShowRating = Convert.ToDouble((lbxTopRated.SelectedItem as ShowList).Rating);
                    string title = (lbxTopRated.SelectedItem as ShowList).Title;
                    AppSettings.Title = (lbxTopRated.SelectedItem as ShowList).Title;
                    if (title == Constants.getMoreLabel)
                    {
                        performanceProgressBar.IsIndeterminate = true;
                        Constants.UIThread = true;
                        topratedCount = topratedCount + Constants.PageSize;
                        lbxTopRated.ItemsSource = OnlineShow.GetTopRatedShows(topratedCount);
                        lbxTopRated.ScrollIntoView(lbxTopRated.Items[topratedCount - Constants.PageSize]);
                        performanceProgressBar.IsIndeterminate = false;
                    }
                    else
                    {
                        if (ResourceHelper.ProjectName == Apps.DownloadManger.ToString())
                        {
                            GetDownloadExtensions();
                           
                        }
                        else
                        {
                            AppState.searchtitle = "";
                            PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                        }
                    }
                    lbxTopRated.SelectedIndex = -1;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxTopRated_SelectionChanged event In Shows.cs file.", ex);
            }
        }

        void Instance_PlayStateChanged(object sender, EventArgs e)
        {
            try
            {
            PlayState playState = BackgroundAudioPlayer.Instance.PlayerState;
            switch (playState)
            {
                case PlayState.Paused:
                    IEnumerable<DependencyObject> cboxes = PageHelper.GetChildsRecursive(lbxRecentlyAdded);

                    foreach (DependencyObject obj in cboxes.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                            {

                                cb.IsIndeterminate = false;
                            }
                        }
                    }

                    break;

                case PlayState.Playing:

                    IEnumerable<DependencyObject> cboxes1 = PageHelper.GetChildsRecursive(lbxRecentlyAdded);

                    foreach (DependencyObject obj in cboxes1.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                            {

                                cb.IsIndeterminate = false;
                            }
                        }
                    }

                    break;

                }
            }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in Instance_PlayStateChanged Method In Shows.cs file.", ex);
            }
        }

        private void lbxRecentlyAdded_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {


                if (lbxRecentlyAdded.SelectedIndex != -1)
                {

                    AppSettings.ShowID = (lbxRecentlyAdded.SelectedItem as ShowList).ShowID.ToString();
                    AppSettings.ShowRating = Convert.ToDouble((lbxRecentlyAdded.SelectedItem as ShowList).Rating);
                    string title = (lbxRecentlyAdded.SelectedItem as ShowList).Title;
                    AppSettings.Title = (lbxRecentlyAdded.SelectedItem as ShowList).Title;
                    if (title == Constants.getMoreLabel)
                    {
                        performanceProgressBar.IsIndeterminate = true;
                        Constants.UIThread = true;
                        recentCount = recentCount + Constants.PageSize;
                        lbxRecentlyAdded.ItemsSource = OnlineShow.GetRecentlyAddedShows(recentCount);
                        lbxRecentlyAdded.ScrollIntoView(lbxRecentlyAdded.Items[recentCount - Constants.PageSize]);
                        performanceProgressBar.IsIndeterminate = false;
                    }
                    else
                    {
                        if (ResourceHelper.ProjectName == Apps.DownloadManger.ToString())
                        {
                            GetDownloadExtensions();
                        }
                        else
                        {
                            AppState.searchtitle = "";
                            PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                        }
                    }

                    lbxRecentlyAdded.SelectedIndex = -1;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxRecentlyAdded_SelectionChanged Method In Shows.cs file.", ex);
            }
        }

        private void lbxCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ResourceHelper.AppName == Apps.Web_Tile.ToString())
                {
                    if (lbxCategory.SelectedIndex != -1)
                    {
                        NavigationService.Navigate(NavigationHelper.getCategoryDetailPageForWeb(lbxCategory.SelectedItem as ShowCategories));
                        lbxCategory.SelectedIndex = -1;
                    }
                }
                else if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
                {
                    if (lbxCategory.SelectedIndex != -1)
                    {
                        NavigationService.Navigate(NavigationHelper.getCategoryDetailPageForWeb(lbxCategory.SelectedItem as ShowCategories));
                        lbxCategory.SelectedIndex = -1;
                    }
                }

                else
                {
                    if (lbxCategory.SelectedIndex != -1)
                    {
                        NavigationService.Navigate(NavigationHelper.getCategoryDetailPage(lbxCategory.SelectedItem as CatageoryTable));
                        lbxCategory.SelectedIndex = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxTopRated_SelectionChanged Method In Videos file", ex);
            }
        }

        private void imgTitle_MouseEnter(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

        void wcDownloadList_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                if (e.BytesReceived < e.TotalBytesToReceive)
                    DownloadManagerHelper.ProgressChangeStatus(e, download);

                    if (e.ProgressPercentage == 100)
                    {
                        var itm = download.Where(i => i.Id == int.Parse(e.UserState.ToString())).FirstOrDefault();
                        Constants.SaveDownloadList.Remove(itm);
                        GetPageDataInBackground();
                    }

            }


            catch (Exception ex)
            {
                string excepmess = "Exception in wb_DownloadProgressChanged Method In Videos file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
                Exceptions.SaveOrSendExceptions("Exception in wcDownloadList_DownloadProgressChanged Method In Shows.cs file.", ex);
            }
        }
     
        void wcDownloadList_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
            DownloadManagerHelper.ReadDownloadStream(e, download);
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in wcDownloadList_OpenReadCompleted Method In Shows.cs file.", ex);
            }
        }

        private void deleterecent_Click(object sender, RoutedEventArgs e)
        {
            try
            {
            ShowDetail detailModel = new ShowDetail();
            detailModel.DeleteDownloadedShow(lbxRecentlyAdded, sender as MenuItem);
            GetPageDataInBackground();
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in deleterecent_Click Method In Shows.cs file.", ex);
            }
        }

        private void deletetoprated_Click(object sender, RoutedEventArgs e)
        {
            try
            {
            ShowDetail detailModel = new ShowDetail();
            detailModel.DeleteDownloadedShow(lbxTopRated, sender as MenuItem);
            GetPageDataInBackground();
        }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in deletetoprated_Click Method In Shows.cs file.", ex);
            }
        }

        void wcYoutubeReadCompleted_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
         DownloadManagerHelper.YoutubeWriteStream(e, download);
        }
            catch (Exception ex)
            {
                
              Exceptions.SaveOrSendExceptions("Exception in wcYoutubeReadCompleted_OpenReadCompleted Method In Shows.cs file.", ex);
            }
        }
        private void btnadd_Click_1(object sender, EventArgs e)
        {
            Constants.DownloadTimer.Stop();
            if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
            {
                PageHelper.NavigateToUserUploadPage(AppResources.UserUploadPageName);
            }
            else
            PageHelper.NavigateToUserUploadPage(AppResources.UserUploadPageName);
        }

        private void ContextMenu_Opened_1(object sender, RoutedEventArgs e)
        {
            try
            {

            //MenuItem selectedItem = sender as MenuItem;
            ContextMenu menu = sender as ContextMenu;
            ListBoxItem selectedListBoxItem = lbxTopRated.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
            int showid = (selectedListBoxItem.Content as ShowList).ShowID;
            //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom" && ResourceHelper.AppName != Apps.Web_Tile.ToString())
            {
                menu.IsOpen = false;
            }
            //else
            //{
            //    menu.IsOpen = true;
            //}
        }
            catch (Exception ex)
            {
               Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_1 Method In Shows.cs file.", ex);
            }
        }

        private void ContextMenu_Opened_2(object sender, RoutedEventArgs e)
        {
            try
            {
            ContextMenu menu = sender as ContextMenu;
            ListBoxItem selectedListBoxItem = lbxRecentlyAdded.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
            int showid = (selectedListBoxItem.Content as ShowList).ShowID;
            //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom" && ResourceHelper.AppName != Apps.Web_Tile.ToString())
            {
                menu.IsOpen = false;
            }
            //else
            //{
            //    menu.IsOpen = true;
            //}
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_2 Method In Shows.cs file.", ex);
            }
        }

        #endregion

        private void lbxTamilAdded_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            try
            {


                if (lbxTamilAdded.SelectedIndex != -1)
                {

                    AppSettings.ShowID = (lbxTamilAdded.SelectedItem as ShowList).ShowID.ToString();
                    AppSettings.ShowRating = Convert.ToDouble((lbxTamilAdded.SelectedItem as ShowList).Rating);
                    string title = (lbxTamilAdded.SelectedItem as ShowList).Title;
                    AppSettings.Title = (lbxTamilAdded.SelectedItem as ShowList).Title;
                    if (title == Constants.getMoreLabel)
                    {
                        performanceProgressBar.IsIndeterminate = true;
                        Constants.UIThread = true;
                        tamilCount = tamilCount + Constants.PageSize;
                        lbxTamilAdded.ItemsSource = OnlineShow.GetTamilAddedShows(tamilCount);
                        lbxTamilAdded.ScrollIntoView(lbxTamilAdded.Items[tamilCount - Constants.PageSize]);
                        performanceProgressBar.IsIndeterminate = false;
                    }
                    else
                    {
                        if (ResourceHelper.ProjectName == Apps.DownloadManger.ToString())
                        {
                            GetDownloadExtensions();

                        }
                        else
                        {
                            AppState.searchtitle = "";
                            PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                        }
                    }
                    lbxTamilAdded.SelectedIndex = -1;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxTamilAdded_SelectionChanged_1 event In Shows.cs file.", ex);
            }
        }

        private void ContextMenu_Opened_3(object sender, RoutedEventArgs e)
        {
            try
            {
                ContextMenu menu = sender as ContextMenu;
                ListBoxItem selectedListBoxItem = lbxTamilAdded.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
                int showid = (selectedListBoxItem.Content as ShowList).ShowID;
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom" && ResourceHelper.AppName != Apps.Web_Tile.ToString())
                {
                    menu.IsOpen = false;
                }
                //else
                //{
                //    menu.IsOpen = true;
                //}
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_3 Method In Shows.cs file.", ex);
            }
        }

        private void deletetamil_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowDetail detailModel = new ShowDetail();
                detailModel.DeleteDownloadedShow(lbxTamilAdded, sender as MenuItem);
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in deletetamil_Click_1 Method In Shows.cs file.", ex);
            }
        }

        //private void lbxUpcomingAdded_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        //{
        //    try
        //    {


        //        if (lbxUpcomingAdded.SelectedIndex != -1)
        //        {

        //            AppSettings.ShowID = (lbxUpcomingAdded.SelectedItem as ShowList).ShowID.ToString();
        //            AppSettings.ShowRating = Convert.ToDouble((lbxUpcomingAdded.SelectedItem as ShowList).Rating);
        //            string title = (lbxUpcomingAdded.SelectedItem as ShowList).Title;
        //            AppSettings.Title = (lbxUpcomingAdded.SelectedItem as ShowList).Title;
        //            if (title == Constants.getMoreLabel)
        //            {
        //                performanceProgressBar.IsIndeterminate = true;
        //                Constants.UIThread = true;
        //                upcomingCount = upcomingCount + Constants.PageSize;
        //                lbxUpcomingAdded.ItemsSource = OnlineShow.GetUpComingAddedShows(upcomingCount);
        //                lbxUpcomingAdded.ScrollIntoView(lbxUpcomingAdded.Items[upcomingCount - Constants.PageSize]);
        //                performanceProgressBar.IsIndeterminate = false;
        //            }
        //            else
        //            {
        //                if (ResourceHelper.ProjectName == Apps.DownloadManger.ToString())
        //                {
        //                    GetDownloadExtensions();
        //                }
        //                else
        //                {
        //                    AppState.searchtitle = "";
        //                    PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
        //                }
        //            }

        //            lbxUpcomingAdded.SelectedIndex = -1;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Exceptions.SaveOrSendExceptions("Exception in lbxUpcomingAdded_SelectionChanged_1 Method In Shows.cs file.", ex);
        //    }
        //}

        //private void deleteupcoming_Click_1(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        ShowDetail detailModel = new ShowDetail();
        //        detailModel.DeleteDownloadedShow(lbxUpcomingAdded, sender as MenuItem);
        //        GetPageDataInBackground();
        //    }
        //    catch (Exception ex)
        //    {

        //        Exceptions.SaveOrSendExceptions("Exception in deleteupcoming_Click_1 Method In Shows.cs file.", ex);
        //    }
        //}

        //private void ContextMenu_Opened_4(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        ContextMenu menu = sender as ContextMenu;
        //        ListBoxItem selectedListBoxItem = lbxUpcomingAdded.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
        //        int showid = (selectedListBoxItem.Content as ShowList).ShowID;
        //        //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
        //        if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom" && ResourceHelper.AppName != Apps.Web_Tile.ToString())
        //        {
        //            menu.IsOpen = false;
        //        }
        //        //else
        //        //{
        //        //    menu.IsOpen = true;
        //        //}
        //    }
        //    catch (Exception ex)
        //    {

        //        Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_4 Method In Shows.cs file.", ex);
        //    }
        //}

      

       
    }
  
  
}